package cn.zhangyong.dbframelearn.dao;

import android.content.Context;

import com.j256.ormlite.dao.Dao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import cn.zhangyong.dbframelearn.bean.Note;
import cn.zhangyong.dbframelearn.db.DBHelper;

/**
 * description:
 * autour: zhangyong
 * date: 2019/4/3 10:34
 * update: 2019/4/3
 * version:
 */
public class NoteDao {

    private Dao<Note,Integer> noteDao;
    private DBHelper dbHelper;

    public NoteDao(Context context){
        dbHelper = DBHelper.getInstance(context);
        try {
            noteDao = dbHelper.getDao(Note.class);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 添加一条记录
     * @param note
     */
    public void add(Note note){
        try {
            noteDao.createOrUpdate(note);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除一条记录
     * @param note
     */
    public void delete(Note note){
        try {
            noteDao.delete(note);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 更新一条记录
     * @param note
     */
    public void update(Note note){
        try {
            noteDao.update(note);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询一条记录
     * @param name
     * @return
     */
    public Note queryForName(String name){
        try {
            List<Note> notes = noteDao.queryForEq("name",name);
            if(notes != null && notes.size()>0){
                Note note = notes.get(0);
                return note;
            }else{
                return null;
            }
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("查找出现异常.");
        }
    }

    /**
     * 查询所有记录
     * @return
     */
    public List<Note> queryForAll(){
        List<Note> notes = new ArrayList<>();
        try {
            notes = noteDao.queryForAll();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return notes;
    }

    public boolean isNoteExit(String name){
        List<Note> notes = null;
        try {
            notes = noteDao.queryForEq("name",name);
            if(notes != null && notes.size() == 1){
                return true;
            }else{
                return false;
            }
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("查找用户异常.");
        }
    }
}
